<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
  >
    <!-- (自动上传)action是上传地址 人资项目不需要 人资项目(手动上传)  -->
    <!-- show-file-list不展示列表 -->
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'

export default {
  name: 'ImageUpload',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    // 检查函数 判断文件的类型还有大小 return  true(继续上传)/false(停止上传)
    beforeAvatarUpload(file) {
      // jpeg png gif bmp

      const isJPG = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 5 // 5M
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG PNG GIF BMP 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    // 选择图片之后上传 https://hang788.s3.cn-north-1.jdcloud-oss.com/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202023-10-13%20235603.png
    uploadImage(params) {
      console.log(params.file)
      const AWS = require('aws-sdk') // 引入aws-sdk
      const s3 = new AWS.S3({ apiVersion: '2006-03-01' }) // 创建s3对象
      s3.endpoint = 'https://s3.cn-north-1.jdcloud-oss.com' // 设置s3的地域名称
      s3.config.update({
        accessKeyId: 'JDC_6A06D558F18F862BA11E534E5182',
        secretAccessKey: '8E6DF0B7E5CCAD966185F308D8F28624',
        s3ForcePathStyle: true,
        signatureVersion: 'v4'
      })
      // 生成随机文件名
      const uuid = uuidv4()

      const params2 = {
        Bucket: 'hang788', // 存储桶名称
        // Key: params.file.name, // 文件名称
        Key: uuid, // 文件名称 用uuidv4()生成随机文件名
        Body: params.file, // 文件内容
        ACL: 'public-read', // 设置文件的权限
        ContentType: params.file.type // 设置文件的类型
      }
      s3.putObject(params2, (err, data) => {
        if (err) {
          this.$message.error('上传失败')
        } else {
          this.$message.success('上传成功')
          const contentType = params.file.type
          const fileType = contentType.substring(contentType.lastIndexOf('/') + 1)
          const imgUrl = 'https://hang788.s3.cn-north-1.jdcloud-oss.com/' + uuid
          this.value = imgUrl
          console.log(imgUrl)
          this.$emit('input', imgUrl) // 通知父组件更新数据}
        }
      })
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
